#include <stdio.h>
#include <math.h>
#include "MathFunctions.h"

#define FLT_MIN 1.175494e-038
double mySqrt_binarysearch(int x)
{
  if (x <= 0)
    return 0;

  double begin = 1;
  double end = x / 2 + 1;
  double mid, lastmid;

  mid = begin + (end - begin) / 2;
  do
  {
    if (mid < x / mid)
      begin = mid;
    else
      end = mid;

    lastmid = mid;
    mid = begin + (end - begin) / 2;
    fprintf(stdout, "Computing sqrt of %g to be %g\n", x, mid);
  } while (abs(lastmid - mid) > FLT_MIN);

  return mid;
}

double mySqrt_newton(int x)
{
  if (x <= 0)
    return 0;

  double res, lastres;

  res = x; //初始值，可以为任意非0的值

  do
  {
    lastres = res;
    res = (res + x / res) / 2;
    fprintf(stdout, "Computing sqrt of %g to be %g\n", x, res);
  } while (abs(lastres - res) > FLT_MIN);

  return res;
}

// a hack square root calculation using simple operations
double mySqrt_simple(double x)
{
  if (x <= 0)
  {
    return 0;
  }

  double result;
  double delta;
  result = x;

  // do ten iterations
  int i;
  for (i = 0; i < 10; ++i)
  {
    if (result <= 0)
    {
      result = 0.1;
    }
    delta = x - (result * result);
    result = result + 0.5 * delta / result;
    fprintf(stdout, "Computing sqrt of %g to be %g\n", x, result);
  }
  return result;
}

float InvSqrt(float x)
{
  float xhalf = 0.5f * x;
  int i = *(int *)&x;
  i = 0x5f375a86 - (i >> 1);
  x = *(float *)&i;
  x = x * (1.5f - xhalf * x * x);
  x = x * (1.5f - xhalf * x * x);
  x = x * (1.5f - xhalf * x * x);

  return 1 / x;
}

double mysqrt(double x)
{
  return mySqrt_simple(x);
}
